<template>
    <div class="container">
        <van-form validate-first class="items" @failed="onFailed" @submit="onSubmit" input-align="right">
          <div class="item center">
            <h4>信息录入</h4>
          </div>
        <!-- 通过 pattern 进行正则校验 -->
            <!-- <van-field v-model="username" readonly label="姓名"  class="item" placeholder=""/> -->
            <van-field v-model="username" label="姓名" required  class="item" :rules="[{ validator:validatorName, message: '请输入姓名' }]" error-message-align="right" placeholder="请输入姓名"/>
            <!-- 允许输入正整数，调起纯数字键盘 -->
            <van-field v-model.trim="mobile" @change="getUserInfo" required class="item" type="digit" maxlength="11" label="手机号" name="validatorPhone" error-message-align="right"
              :rules="[{ validator:validatorPhone, message: '请输入正确的手机号' }]" placeholder="请输入"/>
            <van-field v-model.trim="id_card" :readonly="state==1" required class="item" maxlength="18" label="身份证号" name="validatorIdNum" error-message-align="right"
              :rules="[{ validator:validatorIdNum, message: '请输入正确的身份证号码' }]" placeholder="请输入"/>
            <van-field name="uploader" class="mb20" required label="身份证照片"> 
              <template #input>
                <van-uploader v-model="photo"  :after-read="afterRead" :max-count="1" />
                <!-- :before-read="beforeRead" -->
              </template>
            </van-field>
            <van-field name="uploader" class="mb20" required label="自拍照片">
              <template #input>
                <van-uploader v-model="id_card_photo" :after-read="afterReadSelf" capture :max-count="1" />
              </template>
            </van-field>
           
            <div style="margin: 30px;">
              <van-button round block type="info" :class="{gray:btnGray||state==1}" native-type="submit">
              {{state==0?"提交":"已审核"}}
              </van-button>
            </div>
        </van-form>
    </div>
</template>
<script>
import { Toast } from 'vant';
import axios from 'axios'
export default {
  data() {
    return {
      id:'1',
      username:'',
      mobile:'',
      id_card: '',
      photo:[],
      photoNew:'',
      id_card_photo:[],//自拍照片
      id_card_photoNew:'',
      btnGray:false,
      state:'0'//0待审核1已审核
    };
  },
  created () {
    // this.id = this.$route.params.id||'1'
    // console.log('id',this.id_card_photo)
    document.title="信息录入"
  },
  methods: {
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validatorPhone(val) {
      let reg=/^1(3|4|5|6|7|8|9)\d{9}$/
      return reg.test(val);
    },
    validatorName(val) {
      if(val){
        return true
      }else{
        return false
      }
      
    },
    validatorIdNum(val) {
      let regIdCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      // let regIdCard =/^(\d{18,18}|\d{15,15}|\d{17,17}X)$/
      return regIdCard.test(val);
    },

    onSubmit(){
      if(this.btnGray){
        this.$toast('用户不存在，无法提交');
        return
      }
      if(this.state==1){
        this.$toast('用户信息已审核通过，不能提交');
        return
      }
      // 提交表单且验证通过后触发
      console.log('校验通过，提交了')
      if(!this.photoNew||this.photo.length<=0){
        this.$toast('请先上传身份证照片再提交');
        return
      }else if(!this.id_card_photoNew||this.id_card_photo.length<=0){
        this.$toast('请先上传自拍照片再提交');
        return
      }
      let data={
        id:this.id,
        username:this.username,
        mobile:this.mobile,
        id_card:this.id_card,
        photo:this.photoNew.replace('http://ofzl.oss-cn-shenzhen.aliyuncs.com/',''),
        id_card_photo:this.id_card_photoNew.replace('http://ofzl.oss-cn-shenzhen.aliyuncs.com/',''),
      }

      this.addUser(data)
    },
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    // 返回布尔值
    beforeRead(file) {
      if(this.btnGray){
        this.$toast('用户不存在，无法提交');
        return false
      }
      // if (file.type !== 'image/jpeg') {
      //   Toast('请上传 jpg 格式图片');
      //   return false;
      // }
      // return true;
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file);
      let formData = new FormData();
      formData.append("photo",file.file);
      this.uploadImg(formData,'1')
    },
    afterReadSelf(file) {
      console.log(file);
      let formData = new FormData();
      formData.append("photo",file.file);
      this.uploadImg(formData,'2')
    },
    getUserInfo(){
      this.photoNew=''
      this.username=''
      this.photo=[]
      this.id_card_photoNew=''
      this.id_card_photo=[]
      this.state='0'
      axios({
        method:'post',
        url:'http://fans.officelinking.com/index.php/admin/api/getUser',
        data:{
          mobile:this.mobile,
          // username:this.username,
        }
      }).then((response) =>{          //这里使用了ES6的语法
          console.log(response)       //请求成功返回的数据
          if(response.data.code===0){
            this.id=response.data.data.id
            this.id_card=response.data.data.id_card
            this.mobile=response.data.data.mobile
            if(response.data.data.photo){
              this.photoNew=response.data.data.photo
              this.photo.push({ url: response.data.data.photo });    //回显图片的关键
            }
            if(response.data.data.id_card_photo){
              this.id_card_photoNew=response.data.data.id_card_photo
              this.id_card_photo.push({ url: response.data.data.id_card_photo });    //回显图片的关键
            }
            this.state=response.data.data.state
            this.username=response.data.data.username
            this.btnGray=false;
          }else{
            this.$toast(response.data.msg);
            this.btnGray=true;
            this.id='1'
            this.id_card=''
            this.mobile=''
            this.photoNew=''
            this.photo=[]
            this.id_card_photoNew=''
            this.id_card_photo=[]
            this.state='0'
          }
      }).catch((error) =>{
          console.log(error)
          this.$toast('接口失败');
      })
    },
    uploadImg(data,type){
      axios({
        method:'post',
        url:'http://fans.officelinking.com/index.php/admin/api/uploadFace',
        data,
      }).then((response) =>{          //这里使用了ES6的语法
          console.log(response)       //请求成功返回的数据
          if(response.data.code===0){
            this.$toast('上传图片成功');
            if(type==1){
              this.photoNew=response.data.data
            }
            if(type==2){
              this.id_card_photoNew=response.data.data
            }
          }else{
            this.$toast(response.data.msg);
          }
      }).catch((error) =>{
          console.log(error)
          this.$toast('接口失败');
      })
    },
    addUser(data){
      axios({
        method:'post',
        url:'http://fans.officelinking.com/index.php/admin/api/addUser',
        data,
      }).then((response) =>{          //这里使用了ES6的语法
          console.log(response)       //请求成功返回的数据
          if(response.data.code===0){
            this.$toast('提交用户信息成功');
          }else{
            this.$toast(response.data.msg);
          }
      }).catch((error) =>{
          console.log(error)
          this.$toast('接口失败');
      })
    }
  },
};

</script>
<style lang="scss" scoped>
.container{
  background-color: #f5f5f5;
  // padding-bottom: 20px;
  min-height: 100vh;
  box-sizing: border-box;
  .items{
    .item{
      height: 50px;
      background-color: #fff;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      &.none{
        height:auto;
        background-color: #f5f5f5;
      }
      &.mb0{
        margin-bottom: 0;
        background-color: #fff;
      }
      &.center{
        justify-content: center;
      }

    }
  }
  .mb20{
    margin-bottom: 10px;
    background-color: #fff;
    padding: 10px 16px;
    box-sizing: border-box;
    font-size: 14px;
    .title{
      display: flex;
      height: 30px;
      align-items: center;
    }
  }
  .timeBox{
    margin-bottom: 20px;
    background-color: #fff;
  }
  .gray{
    background-color: #ccc;
    border-color:#ccc;
  }
}
</style>